package com.lagou.edu.sss.session;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Component
public class SessionStorage {

    @Autowired
    private RedisTemplate redisTemplate;

    // private Map<String, Session> sessionMap = new HashMap<>();
    private int timeout = 30; // 分钟

    public void storeSession(String username) {
        // sessionMap.put(username, new Session(new Date(), username));
        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(new Date().getTime());
        calendar.add(Calendar.MINUTE, timeout);
        redisTemplate.opsForValue().set(username, username, timeout, TimeUnit.MINUTES);
    }

    public boolean hasSession(String username) {
        boolean hasSession = false;
        // Session session = sessionMap.get(username);
        // if (session != null) {
        // Calendar calendar = Calendar.getInstance();
        // calendar.setTimeInMillis(session.loginDate.getTime());
        // calendar.add(Calendar.MINUTE, timeout);
        // if (!new Date().after(calendar.getTime())) {
        // hasSession = true;
        // }
        // }
        if (username != null) {
            Object o = redisTemplate.opsForValue().get(username);
            hasSession = o != null;
        }
        return hasSession;
    }

    // class Session {
    // private Date loginDate;
    // private String username;
    //
    // public Session(Date loginDate, String username) {
    // this.loginDate = loginDate;
    // this.username = username;
    // }
    // }
}
